package com.bicycle.statis.service.jobhandler;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bicycle.common.enums.MsgEnums;
import com.bicycle.common.helper.RedisStringHelper;
import com.bicycle.service.cache.DataCacheOprator;
import com.bicycle.service.dto.BaseJsonMsg;
import com.bicycle.service.dto.BicycleSite;
import com.bicycle.service.dto.OrderInfo;
import com.bicycle.service.entity.BicycleBasicsBicycle;
import com.bicycle.service.entity.BicycleCommonEnterprise;
import com.bicycle.service.service.IBicycleBasicsBicycleService;
import com.bicycle.service.service.IBicycleCreateTableService;
import com.bicycle.service.service.IBicycleStatisGlobalService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * XxlJob开发示例（Bean模式）
 * <p>
 * 开发步骤：
 * 1、在Spring Bean实例中，开发Job方法，方式格式要求为 "public ReturnT<String> execute(String param)"
 * 2、为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobLogger.log" 打印执行日志；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Component
public class SampleXxlJob {
    private static Logger logger = LoggerFactory.getLogger(SampleXxlJob.class);

    @Autowired
    private IBicycleCreateTableService createTableService;
    @Autowired
    private IBicycleStatisGlobalService statisGlobalService;
    @Autowired
    private IBicycleBasicsBicycleService bicycleBasicsBicycleService;
    @Resource
    private KafkaTemplate<Object, Object> kafkaTemplate;
    @Autowired
    private RedisStringHelper redisStringHelper;


    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("demoJobHandler")
    public ReturnT<String> demoJobHandler(String param) throws Exception {
        XxlJobLogger.log("XXL-JOB, Hello World.");
        logger.info("hellloasdasdasddasdsd");
        for (int i = 0; i < 5; i++) {
            XxlJobLogger.log("beat at:" + i);
            TimeUnit.SECONDS.sleep(2);
        }
        return ReturnT.SUCCESS;
    }

    /**
     * 创建订单信息表
     *
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("createOrderTableHandler")
    public ReturnT<String> createOrderTableHandler(String param) throws Exception {
        String tableSuffix = "bicycle_data_order_info_";
        for (int i = 1; i <= 3; i++) {
            String tableName = tableSuffix + DateUtil.format(DateUtil.offsetMonth(new Date(), i), "yyyyMM");
            createTableService.createOrderTable(tableName);
        }
        return ReturnT.SUCCESS;
    }

    /**
     * 创建位置信息表
     *
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("createSiteTableHandler")
    public ReturnT<String> createSiteTableHandler(String param) throws Exception {
        String tableSuffix = "bicycle_data_bicycle_site_";
        for (int i = 1; i <= 3; i++) {
            String tableName = tableSuffix + DateUtil.format(DateUtil.offsetDay(new Date(), i), "yyyyMMdd");
            createTableService.createSiteTable(tableName);
        }
        return ReturnT.SUCCESS;
    }


    @XxlJob("statisGlobalDayHandler")
    public ReturnT<String> statisGlobalDayHandler(String param) throws Exception {
        statisGlobalService.statisDay(param);
        return ReturnT.SUCCESS;
    }

    @XxlJob("statisGlobalHourHandler")
    public ReturnT<String> statisGlobalHourHandler(String param) throws Exception {
        statisGlobalService.statisHour(param);
        return ReturnT.SUCCESS;
    }


    @XxlJob("makeDataHandler")
    public ReturnT<String> makeDataHandler(String param) throws Exception {

        QueryWrapper<BicycleBasicsBicycle> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply(" 1 = 1 order by rand() LIMIT 1");
        BicycleBasicsBicycle bicycleBasicsBicycle = bicycleBasicsBicycleService.getOne(queryWrapper);

        DataCacheOprator.getInstance().setRedisStringHelper(redisStringHelper);
        Random random = new Random();
        List<BicycleCommonEnterprise> enterpriseList = DataCacheOprator.getInstance().getEnterpriseList();
        BicycleCommonEnterprise enterprise = enterpriseList.get(random.nextInt(enterpriseList.size()));
        BicycleSite bicycleSite = new BicycleSite();
        bicycleSite.setBicycleNo(bicycleBasicsBicycle.getVehicleNo());
        bicycleSite.setComId(enterprise.getEnterpriseNo());
        bicycleSite.setGnssTime(new Date());
        bicycleSite.setLat(bicycleBasicsBicycle.getLat());
        bicycleSite.setLng(bicycleBasicsBicycle.getLng());
        bicycleSite.setLockState(1);

        BaseJsonMsg baseJsonMsg = new BaseJsonMsg();
        baseJsonMsg.setJsonStr(bicycleSite);
        baseJsonMsg.setType(MsgEnums.MSG_BICYCLE_SITE.getTopicKey());
        kafkaTemplate.send("JR_MT",MsgEnums.MSG_BICYCLE_SITE.getTopicKey(), JSON.toJSONString(baseJsonMsg));

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setBicycleNo(bicycleBasicsBicycle.getVehicleNo());
        orderInfo.setComId(enterprise.getEnterpriseNo());
        orderInfo.setEndLat(bicycleBasicsBicycle.getLat());
        orderInfo.setEndLng(bicycleBasicsBicycle.getLng());
        orderInfo.setEndTime(new Date());
        orderInfo.setOrderMile(0);
        orderInfo.setOrderNo(String.valueOf(System.currentTimeMillis()));
        orderInfo.setStartLat(bicycleBasicsBicycle.getLat());
        orderInfo.setStartLng(bicycleBasicsBicycle.getLng());
        orderInfo.setStartTime(new Date());
        orderInfo.setUploadTime(new Date());
        orderInfo.setUserId(null);

        baseJsonMsg = new BaseJsonMsg();
        baseJsonMsg.setJsonStr(orderInfo);
        baseJsonMsg.setType(MsgEnums.MSG_ORDER.getTopicKey());
        kafkaTemplate.send("JR_MT",MsgEnums.MSG_ORDER.getTopicKey(), JSON.toJSONString(baseJsonMsg));

        return ReturnT.SUCCESS;
    }


}
